package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.service.WebSocketServer;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    private Orders orders;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理订单的异常事务，1：购物车为空，2：地址为空
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook1 = addressBookMapper.getById(userId);
        if (addressBook1 == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.get(shoppingCart);
        if (shoppingCarts == null) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入一个数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook1.getPhone());
        orders.setConsignee(addressBook1.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setAddress(addressBook1.getProvinceName() + addressBook1.getCityName() + addressBook1.getDistrictName() + addressBook1.getDetail());
        this.orders = orders;
        orderMapper.insert(orders);
        //获取插入的订单id
        Long ordersId = orders.getId();
        //向订单明细表插入多条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(ordersId);
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.delete(shoppingCart);
        //返回OrderSubmitVO对象
        return OrderSubmitVO.builder().id(ordersId).orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).build();

    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, this.orders.getId());

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    /**
     * 查询历史订单历史订单分页查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQueryHistoryOrders(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> p = orderMapper.pageQueryHistoryOrders(ordersPageQueryDTO);

        ArrayList<OrderVO> list = new ArrayList<>();
        if (p != null && p.getResult().size() > 0) {
            for (Orders o : p) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(o, orderVO);

                Long orderId = o.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }

        }
        return new PageResult(p.getTotal(), list);


    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {

        Orders orders = orderMapper.getAllByid(id);
        Long ordersId = orders.getId();

        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(ordersId);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;

    }

    /**
     * 取消订单
     *
     * @param id
     */

    @Override
    public void cancleById(Long id) {
        Orders orders = orderMapper.getAllByid(id);
        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setCancelTime(LocalDateTime.now());
        // orders.setCancelReason("用户取消");
        orders.setStatus(Orders.CANCELLED);
        orderMapper.cancleById(orders);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getAllByid(id);
        Long userId = orders.getUserId();
        Long orderId = orders.getId();

        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
        for (OrderDetail orderDetail : orderDetails) {
            Long dishId = orderDetail.getDishId();
            //ShoppingCart shoppingCart = new ShoppingCart();
            if (dishId != null) {

                Dish dish = dishMapper.getById(dishId);
                String dishFlavor1 = orderDetail.getDishFlavor();

                ShoppingCart shoppingCart = ShoppingCart.builder()
                        .name(dish.getName())
                        .image(dish.getImage())
                        .userId(userId)
                        .dishId(dishId)
                        .dishFlavor(dishFlavor1)
                        .number(orderDetail.getNumber())
                        .amount(orderDetail.getAmount())
                        .createTime(LocalDateTime.now())
                        .build();
                shoppingCartMapper.inset(shoppingCart);

            } else {
                Long setmealId = orderDetail.getSetmealId();
                SetmealVO setmealVO = setmealMapper.getSetmealById(setmealId);
                ShoppingCart shoppingCart = ShoppingCart.builder()
                        .name(setmealVO.getName())
                        .image(setmealVO.getImage())
                        .userId(userId)
                        .setmealId(setmealId)
                        .number(orderDetail.getNumber())
                        .amount(orderDetail.getAmount())
                        .createTime(LocalDateTime.now())
                        .build();
                shoppingCartMapper.inset(shoppingCart);
            }
        }


    }

    /**
     * 管理端 分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();
        List<Orders> result = page.getResult();
        if (result != null && result.size() > 0) {
            for (Orders orders1 : result) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders1, orderVO);

                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderVO.getId());

                // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
                List<String> orderDishList = orderDetails.stream().map(x -> {
                    String orderDish = x.getName() + "*" + x.getNumber() + ";";
                    return orderDish;
                }).collect(Collectors.toList());
                String s = String.join("", orderDishList);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(s);
                list.add(orderVO);
            }

        }
        return new PageResult(page.getTotal(), list);

    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);


        // 封装成OrderStatisticsVO对象并返回
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;

    }

    //   接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderMapper.getAllByid(ordersConfirmDTO.getId());
        if (orders != null) {
            orders.setStatus(Orders.CONFIRMED);
            orders.setId(ordersConfirmDTO.getId());
            orderMapper.updaterd(orders);
        }
    }

    //  拒单
    @Override
    public void refuse(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getAllByid(ordersRejectionDTO.getId());
        if (orders != null && orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setCancelTime(LocalDateTime.now());
            orders.setId(ordersRejectionDTO.getId());
            orderMapper.updaterd(orders);
        }
    }

    //  取消订单
    @Override
    public void adminCancleById(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getAllByid(ordersCancelDTO.getId());
        if (orders != null && orders.getStatus() != Orders.COMPLETED) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.adminCancleById(orders);
        }
    }

    /**
     * 订单配送
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getAllByid(id);
        if (orders != null && orders.getStatus() == Orders.CONFIRMED) {
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orders.setId(id);
            orderMapper.updaterd(orders);
        }

    }

    //完成订单
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getAllByid(id);
        if (orders != null && orders.getStatus() == Orders.DELIVERY_IN_PROGRESS) {
            orders.setStatus(Orders.COMPLETED);
            orders.setId(id);
            orderMapper.updaterd(orders);
        }

    }

    // 催单
    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getAllByOrderId(id);
        if (order != null) {
            Map map = new HashMap();
            map.put("type", 2);
            map.put("orderId", order.getId());
            map.put("content", "订单号：" + order.getNumber());
            webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
        }

    }

    // 工作台-获取营业数据
    @Override
    public BusinessDataVO getBusinessData(LocalDateTime endTime,  LocalDateTime beginTime) {


        //获取新增用户
        Integer userCount = userMapper.getNewUserCount(beginTime, endTime);

        //有效订单数
        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        Integer orderCount = orderMapper.getValidOrderCount(map);

        //获得总订单数
        Integer totalCount=orderMapper.getOrderCount(beginTime, endTime);

        //订单完成率
        double l=0;
        if(totalCount!=0){
            l=orderCount/totalCount;
        }

        //营业额
        Double d=orderMapper.getSumAmount(map);
        d=d==null?0:d;

        //平均客单价
        double price=0;
        if(orderCount!=0){
            price=d/orderCount;
        }
      return   BusinessDataVO.builder()
                .newUsers(userCount)
                .orderCompletionRate(l)
                .turnover(d)
                .unitPrice(price)
                .validOrderCount(orderCount)
                .build();

    }
}
